<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pixiv图片生成器</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 1200px;
            margin: 20px auto;
            padding: 0 20px;
            background-color: #f5f5f5;
        }

        .controls {
            background-color: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: center;
        }

        .input-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        input[type="number"], input[type="text"] {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            width: 200px;
        }

        .hint {
            font-size: 12px;
            color: #666;
            max-width: 200px;
        }

        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #45a049;
        }

        .gallery {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }

        .image-item {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transition: transform 0.3s;
            position: relative;
        }

        .image-item:hover {
            transform: translateY(-5px);
        }

        .image-item img {
            width: 100%;
            height: 400px;
            object-fit: cover;
            border-bottom: 1px solid #eee;
            cursor: zoom-in;
        }

        .loading {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 24px;
            color: #666;
        }

        /* 全图查看模态框 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            z-index: 999;
        }

        .modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            max-width: 90%;
            max-height: 90%;
        }

        .modal-tools {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            gap: 10px;
        }

        .close-btn {
            position: fixed;
            top: 20px;
            right: 20px;
            color: white;
            font-size: 30px;
            cursor: pointer;
        }

        /* R18标签样式 */
        .r18-tag {
            position: absolute;
            top: 10px;
            right: 10px;
            background-color: #f44336;
            color: white;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="controls">
        <div class="input-group">
            <input type="number" id="count" min="1" max="10" value="1">
            <span class="hint">生成数量 (1-10)</span>
        </div>
        <div class="input-group">
            <input type="text" id="tags" placeholder="输入搜索标签">
            <span class="hint">多个标签用 | 分隔（示例：萝莉|风景）</span>
        </div>
        <div class="checkbox-group">
            <input type="checkbox" id="r18" checked>
            <label for="r18">R18内容</label>
        </div>
        <button onclick="generateImages()">生成图片</button>
        <button onclick="saveAllImages()" style="background-color: #2196F3;">保存全部</button>
    </div>
    <div class="gallery" id="gallery"></div>
    <div class="loading" id="loading">加载中...</div>

    <!-- 全图查看模态框 -->
    <div class="modal" id="modal" onclick="closeModal()">
        <span class="close-btn">&times;</span>
        <img class="modal-content" id="modalImage">
        <div class="modal-tools">
            <button onclick="saveCurrentImage()">保存当前图片</button>
        </div>
    </div>

    <script>
		let currentImageUrl = '';
		let currentImageData = {};

		async function generateImages() {
			const count = Math.min(Math.max(parseInt(document.getElementById('count').value) || 1, 1), 10);
			const tags = document.getElementById('tags').value.replace(/\s+/g, '').replace(/\|+/g, '|');
			const r18 = document.getElementById('r18').checked ? 1 : 0;
			const gallery = document.getElementById('gallery');
			const loading = document.getElementById('loading');
			
			gallery.innerHTML = '';
			loading.style.display = 'block';

			try {
				const apiUrl = `https://image.anosu.top/pixiv/json?r18=${r18}${tags ? '&keyword=' + encodeURIComponent(tags) : ''}`;
				
				const promises = Array.from({length: count}, () => 
					fetch(apiUrl)
						.then(response => response.json())
				);

				const results = await Promise.all(promises);

				results.forEach(data => {
					if(data && data.length > 0) {
						const item = data[0];
						const imgUrl = item.url;
						const imgContainer = document.createElement('div');
						imgContainer.className = 'image-item';
						imgContainer.innerHTML = `
							${item.r18 ? '<div class="r18-tag">R18</div>' : ''}
							<img src="${imgUrl}" alt="Pixiv图片" 
								 onerror="this.src='//placehold.it/300x400?text=图片加载失败'"
								 data-item='${JSON.stringify(item).replace(/'/g, "&apos;")}'>
						`;
						gallery.appendChild(imgContainer);
					}
				});
			} catch (error) {
				console.error('请求失败:', error);
				alert('图片加载失败，请稍后重试');
			} finally {
				loading.style.display = 'none';
			}
		}

		function showFullImage(url, data) {
			currentImageUrl = url;
			currentImageData = data || {};
			const modal = document.getElementById('modal');
			const modalImg = document.getElementById('modalImage');
			modal.style.display = 'block';
			modalImg.src = url;
			document.body.style.overflow = 'hidden'; // 防止背景滚动
		}

		function closeModal() {
			document.getElementById('modal').style.display = 'none';
			document.body.style.overflow = ''; // 恢复滚动
		}

		function saveCurrentImage() {
			if(!currentImageUrl) return;
			const link = document.createElement('a');
			link.href = currentImageUrl;
			const filename = currentImageData.title 
				? `${currentImageData.title}_${currentImageData.pid}.jpg`.replace(/[^\w\-.]/g, '_')
				: `pixiv_${Date.now()}.jpg`;
			link.download = filename;
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
		}

		function saveAllImages() {
			const images = document.querySelectorAll('.image-item img');
			images.forEach((img, index) => {
				if(img.src.includes('placehold.it')) return;
				setTimeout(() => {
					const link = document.createElement('a');
					link.href = img.src;
					// 尝试获取data-item中的信息
					let filename = `pixiv_${Date.now()}_${index}.jpg`;
					try {
						if(img.dataset.item) {
							const data = JSON.parse(img.dataset.item);
							if(data.title && data.pid) {
								filename = `${data.title}_${data.pid}.jpg`.replace(/[^\w\-.]/g, '_');
							}
						}
					} catch(e) {
						console.log('解析图片信息失败', e);
					}
					link.download = filename;
					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);
				}, index * 300);
			});
		}

		// 事件监听器
		document.addEventListener('DOMContentLoaded', function() {
			// 图片点击事件委托
			document.getElementById('gallery').addEventListener('click', function(e) {
				if (e.target.tagName === 'IMG' && e.target.dataset.item) {
					try {
						const item = JSON.parse(e.target.dataset.item);
						showFullImage(e.target.src, item);
						e.stopPropagation(); // 阻止事件冒泡
					} catch(error) {
						console.error('解析图片数据失败:', error);
					}
				}
			});

			// 模态框点击事件
			document.getElementById('modal').addEventListener('click', function(e) {
				if(e.target === this || e.target.classList.contains('close-btn')) {
					closeModal();
				}
			});

			// 保存按钮点击事件（防止冒泡）
			document.querySelector('.modal-tools').addEventListener('click', function(e) {
				e.stopPropagation();
			});

			// ESC键关闭模态框
			document.addEventListener('keydown', function(e) {
				if(e.key === 'Escape') {
					closeModal();
				}
			});
		});
    </script>
</body>
</html>